package com.pet.framework.baidu;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Map;
import java.util.Map.Entry;

public class WebClient {

	private static final String BASE_URL = "http://api.map.baidu.com";
	private static final String AK  = "GvWSOyCzR7EeSjNRjnaIFS87";
	private static final String SK  = "1ajTmfRj9ir96EFuFBtEsom0tkfTe96L"; 
	
	public static String io(String uri, Map<String, String> params) throws Exception {		
        String paramsStr = toQueryString(params);// put ak in
        String sn = sign(uri, paramsStr);
        String completeUrl = BASE_URL+uri+paramsStr+"&sn="+sn;
        //System.out.println(completeUrl);
        URL url = new URL(completeUrl);
        InputStream in = url.openStream();
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        for (int len = 0; (len = in.read(buffer)) > 0;) {
        	byteBuffer.write(buffer, 0, len);
        }
        in.close();
		return new String(byteBuffer.toByteArray(), "GBK");
	}
	
	public static String sign(String uri, String paramStr) throws Exception{
        String wholeStr = new String(uri + paramStr + SK);
        String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
        return MD5(tempStr);
	}
	

    public static String toQueryString(Map<String, String> params) throws Exception {
		StringBuffer queryString = new StringBuffer();
		for (Entry<String, String> pair : params.entrySet()) {
			queryString.append(pair.getKey() + "=");
			queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&");
		}
		queryString.append("timestamp="+(System.currentTimeMillis()/1000));
		queryString.append("&ak=").append(AK);
		return queryString.toString();
    }

    public static String MD5(String md5) throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] array = md.digest(md5.getBytes());
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < array.length; ++i) {
			int temp = (array[i] & 0xFF) | 0x100;
			String tempStr = Integer.toHexString(temp);
			sb.append(tempStr.substring(1, 3));
		}
		return sb.toString();
	}
}
